do "E:\yungyu\lottery_baby\do\set_environment.do"

clear
set more off

forv i = 97(1)110{
	dis "Year `i'"
	use "$jhq/jhq_`i'.dta", clear
	keep idn marriage_date
	qui gen marriage_year = substr(marriage_date,1,3)
	qui replace marriage_year = substr(marriage_date,1,2) if marriage_year > "200"
	qui replace marriage_year = substr(marriage_date,-2,2) if marriage_year <= "012" | marriage_year > substr("0`i'",-3,3)
	qui destring marriage_year, replace force

	keep idn marriage_year
	qui keep if marriage_year != .

	tab marriage_year
	save "$wdata/marriage_year_`i'.dta", replace
}


use "$jhq/JHQ.dta", clear
keep idn marriage_date
rename marriage_date marriage_year
keep if marriage_year != .
sort idn marriage_year
duplicates drop idn, force

save "$wdata/marriage_year_jhq011.dta", replace

clear
forv i = 93(1)109{
	dis "Year `i'"
	ap using "$public/couple/couple_`i'.dta"
	keep pers_idn year
	sort pers_idn year
	duplicates drop pers_idn, force
}
rename pers_idn idn
rename year marriage_year

save "$wdata/marriage_year_couple.dta", replace

clear
forv i = 97(1)110{
	ap using "$wdata/marriage_year_`i'.dta"
} 

sort idn marriage_year
duplicates drop idn, force

gen source = "jhq302"

merge 1:1 idn using "$wdata/marriage_year_jhq011.dta", update

replace source = "jhq011" if _m == 2 | _m == 4
drop _m

merge 1:1 idn using "$wdata/marriage_year_couple.dta", update

replace source = "couple" if _m == 2 | _m == 4
drop _m

rename idn pers_idn

save "$wdata/marriage_year.dta", replace
